package com.zbu.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zbu.reggie.common.R;
import com.zbu.reggie.config.Log;
import com.zbu.reggie.entity.Category;
import com.zbu.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*
 * 分类管理*/
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /*
    添加分类* */
    @Log
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("category:{}",category);
        categoryService.save(category);
        return R.success("新增分类成功");
    }

    /*分页查询*/
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        //分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //条件构造器 需要排序
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //根据sort进行排序
        wrapper.orderByAsc(Category::getSort);
        //进行分页查询
        categoryService.page(pageInfo, wrapper);
        return R.success(pageInfo);
    }

    /*
     * 删除分类*/
    @Log
    @DeleteMapping
    public R<String> delete(Long ids) {
        log.info("根据id删除,id:{}", ids);
        //如果其它菜品或套餐 关联这个分类 则不能删除 自定义方法实现
        categoryService.remove(ids);

        return R.success("分类信息删除成功");
    }

    /*根据id修改分类信息*/
    @Log
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        log.info("根据id修改分类信息:{}", category);
        categoryService.updateById(category);
//元数据对象处理器 自动处理填充createTime，updateTime，createUser，updateUser
        return R.success("分类信息修改成功");
    }

    /*根据条件查询分类数据*/
    @Log
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        //条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(category.getType() != null, Category::getType, category.getType());//添加一个条件
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);//最后一个按照getUpdateTime降序排列
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }
}
